13705
22294
Eu listo os contatos do Web Service e exibo-os na tableView 'seccionada' dos contatos, como visto na captura de tela.
O problema é que obtenho os mesmos valores de tag para as caixas de seleção da primeira linha da seção A e também da seção S. Classifiquei uma matriz e a exibi na exibição de tabela indexada. Como obter diferentes valores de tag dependendo de indexPath.row independentemente do número de seções exibidas. Aqui está o que eu tentei
Em cellForRowAtIndexPath:
UIButton * checkBox;
if (UI_USER_INTERFACE_IDIOM () == UIUserInterfaceIdiomPhone)
{
checkBox = [[UIButton alloc] initWithFrame: CGRectMake (7, 8, 30, 30)];
}
outro
{
checkBox = [[UIButton alloc] initWithFrame: CGRectMake (15, 13, 30, 30)];
}
// int cnt = 0;
// for (int i = indexPath.section - 1; i> 0; i--)
// {
// cnt + = [[objectsForCharacters objectForKey: [arrayOfCharacters objectAtIndex: i]] count]; // arrayOfCharachters tem caracteres de 'A' a 'Z'
//}
//checkBox.tag = cnt + indexPath.row;
[checkBox setImage: [UIImage imageNamed: @ "checkBox.png"] forState: UIControlStateNormal];
[checkBox addTarget: self action: @selector (checkBoxClicked :) forControlEvents: UIControlEventTouchUpInside];
[checkBox setTag: indexPath.row];
[cell.contentView addSubview: checkBox];
célula de retorno;
}
- (vazio) checkBoxClicked: (id) remetente
{
CGPoint buttonPosition = [remetente convertPoint: CGPointZero toView: self.tableViewContact];
NSIndexPath * indexPath = [self.tableViewContact indexPathForRowAtPoint: buttonPosition];
UIButton * tappedButton = (UIButton *) remetente;
NSLog (@ "Número da etiqueta =% d", [etiqueta do remetente]);
if ([tappedButton.currentImage isEqual: [UIImage imageNamed: @ "checkBox.png"]])
{
[setImage do remetente: [UIImage imageNamed: @ "checkBoxMarked.png"] forState: UIControlStateNormal];
if (indexPath! = Nil)
{
NSString * finalIntId = [mutableArrayOfIds objectAtIndex: indexPath.row]; // armazenar ids de caixa de seleção em mutableArrayOfIds
NSLog (@ "ID do botão marcado marcado =% @", finalIntId);
[arrayOfIds addObject: finalIntId];
}
// NSString * finalIntId = [mutableArrayOfIds objectAtIndex: tappedButton.tag];
// NSString * finalIntId = [mutableArrayOfIds objectAtIndex: indexPath.row];
}
outro
{
[sender setImage: [UIImage imageNamed: @ "checkBox.png"] forState: UIControlStateNormal];
NSLog (@ "Não verificado");
// [arrayOfIds removeObjectAtIndex: tappedButton.tag];
}
}
- (NSString *) tableView: (UITableView *) tableView titleForHeaderInSection: (NSInteger) section {
if ([arrayOfCharacters count] == ​​0)
{
Retorna @"";
}
return [NSString stringWithFormat: @ "% @", [arrayOfCharacters objectAtIndex: section]];
}
- (NSArray *) sectionIndexTitlesForTableView: (UITableView *) tableView
{
NSArray * toBeReturned = [NSArray arrayWithArray:
[@ "A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | # "
componentsSeparatedByString: @ "|"]];
return toBeReturned;
}
- (NSInteger) tableView: (UITableView *) tableView sectionForSectionIndexTitle: (NSString *) title atIndex: (NSInteger) index
{
NSInteger count = 0;
para (caractere NSString * em arrayOfCharacters) {
if ([character isEqualToString: title]) {
contagem de retorno;
}
contagem ++;
}
return 0;
}
- (NSInteger) numberOfSectionsInTableView: (UITableView *) tableView
{
return [arrayOfCharacters count];
// return 1;
}
- (NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: seção (NSInteger)
{
// return [mutableArray count];
return [[objectsForCharacters objectForKey: [arrayOfCharacters objectAtIndex: section]] count];
} 
você está definindo o mesmo valor de tag para todas as seções que têm a mesma linha.
O indexPath tem duas propriedades, {seção, linha}.
Digamos que a seção A tenha duas linhas,
para row1 -> indexPath.section = 0, indexPath.row = 0;
para row2-> indexPath.section = 0, indexPath.row = 1;
Vamos dizer que a seção S tem duas linhas,
para linha1 -> indexPath.section = 1, indexPath.row = 0;
para row2-> indexPath.section = 1, indexPath.row = 1;
Portanto, para a linha 1 da seção A e linha 1 da seção S, você está definindo o mesmo valor de tag que é 0. Este é o seu problema.
Tente definir o valor da tag como abaixo.
button.tag = indexPath.section * 1000 + indexPath.row;
ao recuperar a seção e linha,
Seção NSInteger = (button.tag) / 1000;
NSInteger row = (button.tag)% 1000;
|
Experimente isso ...
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
estático NSString * CellIdentifier = @ "Cell";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: CellIdentifier];
}
UIButton * checkBox = [[UIButton alloc] initWithFrame: CGRectMake (280, 10, 50, 44)];
checkBox.backgroundColor = [UIColor orangeColor];
[checkBox addTarget: self action: @selector (checkBoxClicked: event:) forControlEvents: UIControlEventTouchUpInside];
[checkBox setTag: indexPath.row];
[cell.contentView addSubview: checkBox];
célula de retorno;
}
- (void) checkBoxClicked: (id) evento do remetente: (id) evento
{
NSSet * toca = [evento allTouches];
UITouch * touch = [toca qualquer objeto];
CGPoint currentTouchPosition = [toque em locationInView: self.tv]; // aqui tv é objeto TableView
NSIndexPath * indexPath = [self.tv indexPathForRowAtPoint: currentTouchPosition];
NSLog (@ "valor de indePath.section% d, indexPath.row% d", indexPath.section, indexPath.row);
}
|
Isso está acontecendo porque você está atribuindo tag aos botões INDEPENDENTES das seções.
Ambas as primeiras linhas das seções A e S têm linha = 0. então a marca atribuída a seus respectivos botões é 0. Você deve atribuí-los mantendo referência às suas seções.
Eu sugeriria atribuir uma dica de acessibilidade com um formulário separado por vírgulas contendo Seção, Linha.
E no seu método
- (vazio) checkBoxClicked: (id) remetente
{
// escolha a string de forma separada por vírgulas. A primeira é a sua seção, a segunda é a linha.
}
a segunda opção é Faça o que estiver fazendo e implemente seu método Button assim.
CGPoint buttonPosition = [remetente convertPoint: CGPointZero toView: self.tableView];
NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: buttonPosition];
if (indexPath! = nil)
{
... indexpath.section é sua seção, index path.row é sua linha.
}
Também existe a terceira opção.
em cellforRowAtIndexpath atribua um título ao botão
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
[btn setTitle: <# Your Row #> forState: UIControlStateDisabled];
[btn setTag <#Sua seção #>];
portanto, ao receber em seu Método de botão, você pode ter Seção (Tag) e Linha (Título para o estado Desativado).
- (void) checkBoxClicked: (id) sender {[button titleForState: UIControlStateDisabled]; // sua linha
button.tag // sua seção}
|
Experimente isso!
Cada seção você pode saber a contagem da seção certa e, em seguida, adicionar a contagem da linha individual.
[[fieldTitlesList objectAtIndex: indexPath.section - 1] contagem] + indexPath.row
Onde fieldTitlesList é a matriz de suas seções.
|
Eu adicionei o seguinte código que resolveu meu problema
NSInteger rowNumber = 0;
para (NSInteger i = 0; i